package mgodb

import (
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
	"time"

	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
)

// cUserType 用户类型管理表名
const cUserType = "oper_user_type"

// UserType 用户类型管理
type UserType struct {
	DB *mongo.DB
}

// Init 初始化
func (a *UserType) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cUserType, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"record_id"},
			Unique: true,
		})
		c.EnsureIndexKey("code", "deleted")
		c.EnsureIndexKey("deleted")
		c.EnsureIndexKey("deleted", "status")
		return nil
	})

	var val model.IUserType = a
	g.Provide(&inject.Object{Value: val, Name: "IUserType"})
}

// QueryPage 查询分页数据
func (a *UserType) QueryPage(params schema.UserTypeQueryParam, pageIndex, pageSize uint) (int64, []*schema.UserTypeQueryResult, error) {
	query := bson.M{
		"deleted": 0,
	}

	if v := params.Status; v != 0 {
		query["status"] = v
	}

	if v := params.Name; v != "" {
		query["name"] = bson.M{"$regex": v}
	}

	var total int64
	var items []*schema.UserTypeQueryResult
	err := a.DB.C(cUserType, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		total = int64(n)
		if total == 0 {
			return nil
		}

		return c.Find(query).Sort("code").Skip(int((pageIndex - 1) * pageSize)).Limit(int(pageSize)).All(&items)
	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	}

	return total, items, nil
}

// QuerySelect 查询选择数据
func (a *UserType) QuerySelect(params schema.UserTypeSelectParam) ([]*schema.UserTypeSelect, error) {
	query := bson.M{
		"deleted": 0,
		"status":  1,
	}

	var items []*schema.UserTypeSelect
	err := a.DB.C(cUserType, func(c *mgo.Collection) error {
		return c.Find(query).Sort("code").All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "查询选择数据发生错误")
	}
	return items, nil
}

// Get 精确查询数据
func (a *UserType) Get(recordID string) (*schema.UserType, error) {
	var item schema.UserType
	err := a.DB.C(cUserType, func(c *mgo.Collection) error {
		return c.Find(bson.M{"record_id": recordID}).One(&item)
	})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, errors.Wrapf(err, "精确查询数据发生错误")
	}
	return &item, nil
}

// GetByCode 根据编号获取数据
func (a *UserType) GetByCode(code string) (*schema.UserType, error) {
	var item schema.UserType
	err := a.DB.C(cUserType, func(c *mgo.Collection) error {
		return c.Find(bson.M{"code": code, "deleted": 0}).One(&item)
	})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, errors.Wrapf(err, "根据编号获取数据发生错误")
	}
	return &item, nil
}

// CheckCode 检查编号是否存在
func (a *UserType) CheckCode(code string) (bool, error) {
	var exists bool
	err := a.DB.C(cUserType, func(c *mgo.Collection) error {
		n, err := c.Find(bson.M{"deleted": 0, "code": code}).Count()
		if err != nil {
			return err
		}
		exists = n > 0
		return nil
	})
	if err != nil {
		return false, errors.Wrapf(err, "检查编号是否存在发生错误")
	}

	return exists, nil
}

// Create 创建数据
func (a *UserType) Create(item *schema.UserType) error {
	err := a.DB.C(cUserType, func(c *mgo.Collection) error {
		id, err := a.DB.IncrID(cUserType)
		if err != nil {
			return err
		}
		item.ID = id
		return c.Insert(item)
	})
	if err != nil {
		return errors.Wrapf(err, "创建数据发生错误")
	}

	return nil
}

// Update 更新数据
func (a *UserType) Update(recordID string, info map[string]interface{}) error {
	err := a.DB.C(cUserType, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "更新数据发生错误")
	}
	return nil
}

// Delete 删除数据
func (a *UserType) Delete(recordID string) error {
	info := map[string]interface{}{
		"deleted": time.Now().Unix(),
	}
	err := a.DB.C(cUserType, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "删除数据发生错误")
	}
	return nil
}
